package com.example.onlineanswer.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlineanswer.model.entity.Answer;
import com.example.onlineanswer.model.vo.AnswerStatisticsVO;
import com.example.onlineanswer.model.vo.UserAnswerVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 答案Mapper接口
 */
@Mapper
public interface AnswerMapper extends BaseMapper<Answer> {

    /**
     * 获取用户在某场竞赛中的答题记录
     *
     * @param userId    用户ID
     * @param contestId 竞赛ID
     * @return 答题记录列表
     */
    @Select("SELECT a.*, q.content as question_content, q.order_num " +
            "FROM answer_record a " +
            "LEFT JOIN question q ON a.question_id = q.id " +
            "JOIN participation p ON a.participation_id = p.id " +
            "WHERE p.user_id = #{userId} AND p.contest_id = #{contestId} AND a.is_deleted = 0 " +
            "ORDER BY q.order_num ASC")
    List<UserAnswerVO> getUserAnswersByContestId(@Param("userId") Long userId, @Param("contestId") Long contestId);

    /**
     * 查询指定竞赛的所有答题记录（分页）
     *
     * @param page      分页参数
     * @param contestId 竞赛ID
     * @param questionId 题目ID（可选）
     * @param userId    用户ID（可选）
     * @param isCorrect 是否正确（可选）
     * @return 答题记录列表
     */
    @Select("<script>" +
            "SELECT a.*, u.username as user_name, q.content as question_content " +
            "FROM answer_record a " +
            "LEFT JOIN question q ON a.question_id = q.id " +
            "JOIN participation p ON a.participation_id = p.id " +
            "LEFT JOIN sys_user u ON p.user_id = u.id " +
            "WHERE p.contest_id = #{contestId} AND a.is_deleted = 0 " +
            "<if test='questionId != null'> AND a.question_id = #{questionId} </if> " +
            "<if test='userId != null'> AND p.user_id = #{userId} </if> " +
            "<if test='isCorrect != null'> AND a.is_correct = #{isCorrect} </if> " +
            "ORDER BY a.create_time DESC" +
            "</script>")
    IPage<UserAnswerVO> pageContestAnswers(Page<UserAnswerVO> page,
                                           @Param("contestId") Long contestId,
                                           @Param("questionId") Long questionId,
                                           @Param("userId") Long userId,
                                           @Param("isCorrect") Boolean isCorrect);

    /**
     * 获取指定竞赛中特定题目的答题统计
     *
     * @param contestId  竞赛ID
     * @param questionId 题目ID
     * @return 答题统计
     */
    @Select("SELECT " +
            "COUNT(*) as total_answers, " +
            "SUM(CASE WHEN a.is_correct = 1 THEN 1 ELSE 0 END) as correct_count, " +
            "SUM(CASE WHEN a.is_correct = 0 THEN 1 ELSE 0 END) as wrong_count " +
            "FROM answer_record a " +
            "JOIN participation p ON a.participation_id = p.id " +
            "WHERE p.contest_id = #{contestId} AND a.question_id = #{questionId} AND a.is_deleted = 0")
    AnswerStatisticsVO getQuestionAnswerStatistics(@Param("contestId") Long contestId, @Param("questionId") Long questionId);

    /**
     * 检查用户是否已回答过指定题目
     *
     * @param userId    用户ID
     * @param contestId 竞赛ID
     * @param questionId 题目ID
     * @return 答案ID（如果存在）
     */
    @Select("SELECT a.id FROM answer_record a " +
            "JOIN participation p ON a.participation_id = p.id " +
            "WHERE p.user_id = #{userId} AND p.contest_id = #{contestId} " +
            "AND a.question_id = #{questionId} AND a.is_deleted = 0 " +
            "LIMIT 1")
    Long checkUserAnswerExists(@Param("userId") Long userId, 
                               @Param("contestId") Long contestId, 
                               @Param("questionId") Long questionId);

    /**
     * 更新答案审核状态
     *
     * @param id     答案ID
     * @param status 状态
     * @return 影响行数
     */
    @Update("UPDATE answer_record SET status = #{status}, update_time = NOW() " +
            "WHERE id = #{id}")
    int updateAnswerStatus(@Param("id") Long id, @Param("status") Integer status);

    /**
     * 获取用户在竞赛中的正确答题数
     *
     * @param userId    用户ID
     * @param contestId 竞赛ID
     * @return 正确数量
     */
    @Select("SELECT COUNT(*) FROM answer_record a " +
            "JOIN participation p ON a.participation_id = p.id " +
            "WHERE p.user_id = #{userId} AND p.contest_id = #{contestId} " +
            "AND a.is_correct = 1 AND a.is_deleted = 0")
    int countUserCorrectAnswers(@Param("userId") Long userId, @Param("contestId") Long contestId);

    /**
     * 获取用户在竞赛中的答题总数
     *
     * @param contestId 竞赛ID
     * @param userId    用户ID
     * @return 答题总数
     */
    @Select("SELECT COUNT(*) FROM answer_record a " +
            "JOIN participation p ON a.participation_id = p.id " +
            "WHERE p.contest_id = #{contestId} AND p.user_id = #{userId} AND a.is_deleted = 0")
    Integer getUserAnswerCountByContestId(@Param("contestId") Long contestId, @Param("userId") Long userId);
} 